<?php

// +----------------------------------------------------------------------
// | 星数 [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2023~2024 http://xsframe.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: guiHai <786824455@qq.com>
// +----------------------------------------------------------------------

namespace xsframe\base;


use xsframe\facade\service\SysMemberServiceFacade;

abstract class ApiBaseController extends BaseController
{
    protected $clientBaseType = 'api';

    protected function _initialize()
    {
        parent::_initialize(); // TODO: Change the autogenerated stub

        if (method_exists($this, '_api_initialize')) {
            $this->_api_initialize();
        }
    }

    // 初始化
    protected function _api_initialize()
    {
        // 解决重复提交与跨域问题 start
        header('Access-Control-Allow-Origin:*');
        header("Access-Control-Allow-Headers: Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With , X-Access-Token");
        header('Access-Control-Allow-Methods: PUT,POST,GET,DELETE,OPTIONS');

        if ($this->request->method() === "OPTIONS") {
            exit();
        }
        // 解决重复提交与跨域问题 end
    }

    /**
     * 正确的数组数据
     * @param array $data
     * @param string $code
     * @param string $message
     * @return \think\response\Json
     */
    protected function success(array $data = [], string $code = "200", string $message = 'success'): \think\response\Json
    {
        $code = $data['code'] ?? $code;
        $message = $data['msg'] ?? $message;

        $retData = [
            'code' => (string)$code,
            'msg'  => $message,
            'data' => $data
        ];
        return json($retData);
    }

    /**
     * 错误的数组数据
     * @param string $message
     * @param string $code
     * @return array
     */
    protected function error(string $message = 'fail', string $code = "404"): array
    {
        $code = $data['code'] ?? $code;
        $message = $data['msg'] ?? $message;

        $retData = [
            'code' => (string)$code,
            'msg'  => $message,
            'data' => [],
        ];
        die(json_encode($retData));
    }

    // 默认获取userid
    protected function getUserId()
    {
        $this->userId = SysMemberServiceFacade::getUserId();
        return $this->userId;
    }
}